package com.imot.aop;

import com.imot.annotation.RequiresPermission;
import com.imot.constant.code.ResponseCode;
import com.imot.mapper.SecurityMapper;
import com.imot.securityenum.PermissionEnum;
import com.imot.utils.JwtUtil;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * ClassName: SecurityAspect
 * Description: 切面类，目的是作鉴权功能
 * date: 2023/10/8 19:36
 *
 * @author imot-jiah.wang
 */
//@Aspect
//@Component
public class SecurityAspect {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityMapper securityMapper;

    @Before("@annotation(com.imot.annotation.RequiresPermission)")
    public void beforeAdvice(JoinPoint joinPoint){
        //获取方法签名，得到注解上的value值
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        RequiresPermission annotation = methodSignature.getMethod().getAnnotation(RequiresPermission.class);

        //获取token得到用户id
        PermissionEnum permission = annotation.value();
        String token = request.getHeader("token");
        String userId = JwtUtil.getNumberIdByJwtToken(token);
        Integer id = Integer.valueOf(userId);
        //从用户得到他的用户权限
        List<PermissionEnum> perminssionList = securityMapper.getPermission(id);
        if (perminssionList.contains(permission)){
            return;
        }

        throw new RuntimeException(ResponseCode.ACCOUNT_NO_PERMISSIONS_ACCESS.val()+ResponseCode.ACCOUNT_NO_PERMISSIONS_ACCESS.msg());

    }
}

